const lessUsers = require("../models/lessUsers");
const { sign } = require("../utils/jwt");
const { setJson } = require("../utils/index");

// 注册
exports.register = (req, res) => {
  const { body: { user, pass, rePass } } = req;
  if (pass !== rePass) return setJson(res, 400, "两次密码不一致", null)
  lessUsers
    .find({ user })
    .then(data => {
      if (data.length) return setJson(res, 400, "用户已存在", null)
      lessUsers
        .create({ user, pass })
        .then(() => {
          setJson(res, 200, "注册成功", null)
        })
        .catch(error => {
          setJson(res, 0, "注册失败", error)
        })
    })
    .catch(error => {
      setJson(res, 0, "注册失败", error)
    })
}
// 登录
exports.login = (req, res) => {
  const { body } = req;
  const { user, pass } = body;
  if (!user || !pass) return setJson(res, 400, "请正确输入账号密码", null);
  lessUsers
    .findOne({ user })
    .select({ createdAt: 0, updatedAt: 0, __v: 0 })
    .exec((error, data) => {
      if (!error) {
        if (!data) return setJson(res, 400, "用户不存在", null)
        if (user.toString() === data.user && pass.toString() === data.pass) {
          const token = sign({ user })
          const result = {
            userId: data._id,
            user: data.user,
            token
          }
          setJson(res, 200, "登录成功", result)
        } else {
          setJson(res, 400, "请正确输入密码", null)
        }
      } else {
        setJson(res, 0, "登录失败", error)
      }
    })
}